import { message } from "antd";
import Axios, { AxiosInstance } from "axios";
import { Storage } from "./auth";
import { setLoginModalVisibleAct } from "../store/actions";
import { store } from "../../App";
// 响应体
export interface IResBody {
  code: number; // 状态码
  msg: string; // 提示信息
  data?: any; // 数据
}

export enum ResBodyCode {
  FAIL = 0, //请求失败
  OK = 1, //请求成功
  UNAUTH = 2, //Token不合法
  PARAM_VALID_FAIL = 3 //表单验证失败,必要参数未通过验证,如账户密码为空
}

interface IProps {
  setLoginModalVisible: (visible: boolean) => void;
}

export class MyAxios {
  static axios: AxiosInstance;

  constructor() {
    console.log("constructor:Axios实例");
    // 保证不重复初始化
    if (MyAxios.axios === undefined) {
      MyAxios.init();
    }
  }

  static getToken() {
    return { accessToken: Storage.getToken() };
  }

  private static init() {
    console.log("init:Axios实例");
    MyAxios.axios = Axios.create({
      baseURL: "http://api.ehxproxy.com"
    });
    MyAxios.axios.interceptors.response.use(
      ({ data, status }) => {
        console.log("httpStatus", status);
        const resData: IResBody = data;
        console.log(resData);
        // 判断状态码

        if (status !== 200) {
          message.error("请检查您的网络连接");
          return;
        } else {
          switch (resData.code) {
            case ResBodyCode.UNAUTH: {
              message.error("登录已过期,请重新登录");
              // todo 弹出登录弹框
              store.dispatch(setLoginModalVisibleAct(true));
              break;
            }
            case ResBodyCode.FAIL: {
              message.error(resData.msg);
              // 返回一个promise到catch代码块中
              return Promise.reject({
                msg: resData.msg
              });
            }
            case ResBodyCode.PARAM_VALID_FAIL: {
              //表单验证失败,缺少必要参数
              message.error(resData.msg);
              return Promise.reject({
                msg: resData.msg
              });
            }
          }
        }
        // message.success("请求成功");
        return data;
      },
      err => {
        // 当http状态为不等于200时触发
        console.log("errerr", err);
        message.error("请检查您的网络连接," + err.toString());
        // 将错误信息返回给catch代码块
        return Promise.reject({
          msg: err
        });
      }
    );
  }
}
